<template>
  <div class="comment">
    <div class="submitbox">
      <h3>提交评论</h3>
      <div>
        <group>
          <x-textarea v-model="txtValue" placeholder="请输入内容"></x-textarea>
        </group>
        <x-button type="primary" mini @click.native="comPost">发表</x-button>
      </div>
    </div>
    <div class="commentbox">
      <h3 class="line">评论详情</h3>
      <ul>
        <li v-for="(item,index ) in comList" :key="index">
          <h4 class="comment-content">{{item.content}}</h4>
          <p>
            <span class="comment-user">{{item.user_name}}</span>
            <span class="comment-time">{{item.add_time|ctime}}</span>
          </p>
        </li>
      </ul>
    </div>
    <div class="button-group">
      <x-button type="primary" @click.native="loadingMore" v-if="hasMore">加载更多</x-button>
      <x-button type="warn" v-else>没有更多了</x-button>
    </div>
    <toast v-model="isEmpty">评论不能为空</toast>
    <toast v-model="isSuccess">评论成功</toast>
  </div>
</template>

<script>
// import myheader from '@/components/myheader'
import qs from 'qs'
import { XTextarea, XButton, Group, Toast } from 'vux'
import { getCommentList, postComment } from '@/api'
export default {
  props: ['id'],
  components: {
    // myheader,
    XTextarea,
    XButton,
    Group,
    Toast
  },
  data () {
    return {
      txtValue: '',
      comList: [],
      pageIndex: 1,
      hasMore: true,
      isEmpty: false,
      isSuccess: false
    }
  },
  mounted () {
    this.initComList()
  },
  methods: {
    initComList () {
      getCommentList(this.id, this.pageIndex).then(res => {
        if (res.message.length < 10) {
          this.hasMore = false
        }
        let oldList = this.comList
        this.comList = [...oldList, ...res.message]
      })
    },
    // 加载更多
    loadingMore () {
      // console.log(123)
      this.pageIndex += 1
      this.initComList()
      // 判断数组长度
    },
    comPost () {
      if (this.txtValue.trim() === '') {
        this.isEmpty = true
      } else {
        let obj = { content: this.txtValue }
        postComment(this.id, qs.stringify(obj))
          .then(res => {
            console.log(obj)
            console.log(res)
            this.isSuccess = true
            this.txtValue = ''
            this.comList = []
            this.initComList()
          })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.inputbox {
  border: 1px solid #999;
}
.comment h3 {
  font-weight: bold;
  margin: 10px 0;
  font-size: 14px;
}
.line {
  border-top: 1px solid #999;
  padding-top: 10px;
}
.commentbox{
  li:not(:last-child) {
    border-bottom: 1px solid #999;
    margin: 5px 0;
  }
  p {
    font-size: 14px;
  }
  .comment-content {
    color: #999;
    font-size: 14px;
  }
}
.comment-user, .comment-time {
  font-size: 12px;
  color: #26a2ff;
}

</style>
